package cn.tannn.ops.util;


import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.ops.pwd.controller.vo.RSAKey;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * rsa加密
 *
 * @author tnnn
 * @version V1.0
 * @date 2023-02-20 16:03
 */
public class RasUtil {

    private final static String ALGORITHM_RSA = "RSA";

    /**
     * 通过公钥字符串获取 RSAPublicKey
     */
    public static RSAPublicKey loadPublicKeyByStr(String publicKey) throws Exception {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            byte[] keyBytes = Base64.getDecoder().decode(publicKey);
            X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
            return (RSAPublicKey) keyFactory.generatePublic(spec);
        } catch (NoSuchAlgorithmException e) {
            throw new NoSuchAlgorithmException("无此算法", e);
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeySpecException("公钥非法", e);
        } catch (NullPointerException e) {
            throw new BusinessException("公钥数据为空", e);
        }
    }

    /**
     * 通过私钥字符串获取 RSAPrivateKey
     */
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKey) throws Exception {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            byte[] keyBytes = Base64.getDecoder().decode(privateKey);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            return (RSAPrivateKey) keyFactory.generatePrivate(spec);
        } catch (NoSuchAlgorithmException e) {
            throw new NoSuchAlgorithmException("无此算法", e);
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeySpecException("私钥非法", e);
        } catch (NullPointerException e) {
            throw new BusinessException("私钥数据为空", e);
        }
    }

    /**
     * 生成公钥，私钥的密钥对
     *
     * @param keysize  keysize the keysize. This is an (默认1024)
     */
    public static RSAKey getRSAKeyString(int keysize) throws NoSuchAlgorithmException{
        if(keysize==0){keysize=1024;}
        //密钥对生成，生成规范-RSA算法
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA);
        //初始化模长
        keyPairGen.initialize(keysize);
        //生成密钥对
        KeyPair keyPair = keyPairGen.generateKeyPair();

        String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
        return new RSAKey(publicKey, privateKey);
    }


}
